<template>
  <div class="swiper-container">
    <!-- Main Slides -->
    <section v-for="(slide, index) in slidesData" :key="`slide-${index}`" class="slide"
      :class="{ 'slide--active': currentIndex === index }">
      <div class="slide__outer">
        <div class="slide__inner">
          <div class="slide__content" :style="{ backgroundColor: slide.bg_color }">
            <div class="slide__container">
              <h2 class="slide__heading">{{ slide.title }}</h2>
              <figure class="slide__img-cont" v-if="slide.description">
                <img class="slide__img" :src="slide.description" :alt="slide.title" />
              </figure>
            </div>
          </div>
        </div>
      </div>
    </section>
    <!-- Overlay -->
    <div class="overlay-wrapper">
      <section class="overlay">
        <div class="overlay__content">
          <p class="overlay__count">0<span class="count">{{ currentIndex + 1 }}</span></p>
          <figure class="overlay__img-cont">
            <img v-for="(slide, index) in slidesData" :key="`overlay-img-${index}`" class="image" :src="slide.image_url"
              :alt="slide.title" :class="{ 'image--active': currentIndex === index }" />
          </figure>
        </div>
      </section>
    </div>

    <!-- Navigation Controls -->
    <!-- 临时解决页面滚动button显示问题 -->
    <button class="swiper-button swiper-button--prev" @click="prevSlide" v-show="floorSection === 'swiper'">‹</button>
    <button class="swiper-button swiper-button--next" @click="nextSlide" v-show="floorSection === 'swiper'">›</button>

    <!-- Footer -->
    <footer>
      <a href="https://greensock.com/docs/v3/Plugins/ScrollTrigger/static.observe()">ScrollTrigger.observe()</a>
      <p>$gsap demo{{ floorSection }}</p>
    </footer>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from 'vue'
import type { Slider } from "~/types/page-admin"

const props = defineProps<{
  slidesData?: Slider[],
  floorSection?: string
}>();

const { $gsap } = useNuxtApp()

const currentIndex = ref(0)
const autoPlayInterval = ref<NodeJS.Timeout | null>(null)
const autoPlayDelay = 3000
const isAnimating = ref(false)

// GSAP animation function
const gotoSection = (index: number, direction: number) => {
  if (isAnimating.value) return

  isAnimating.value = true
  index = wrapIndex(index)

  const tl = $gsap.timeline({
    defaults: { duration: 1, ease: 'expo.inOut' },
    onComplete: () => {
      isAnimating.value = false
      currentIndex.value = index
    }
  })

  const currentSection = document.querySelector(`.slide:nth-child(${currentIndex.value + 1})`)
  const nextSection = document.querySelector(`.slide:nth-child(${index + 1})`)

  const currentHeading = currentSection?.querySelector('.slide__heading')
  const nextHeading = nextSection?.querySelector('.slide__heading')

  const outerWrappers = $gsap.utils.toArray('.slide__outer')
  const innerWrappers = $gsap.utils.toArray('.slide__inner')
  const images = $gsap.utils.toArray('.image')
  const slideImages = $gsap.utils.toArray('.slide__img')
  const count = document.querySelector('.count')

  // Animation sequence
  tl.set(count, { text: index + 1 }, 0.32)
    .set(images, { zIndex: 0, autoAlpha: 0 })
    .set([currentSection, images[index]], { zIndex: 1, autoAlpha: 1 })
    .set([nextSection, images[currentIndex.value]], { zIndex: 2, autoAlpha: 1 })
    .fromTo(
      outerWrappers[index],
      { xPercent: 100 * direction },
      { xPercent: 0 },
      0
    )
    .fromTo(
      innerWrappers[index],
      { xPercent: -100 * direction },
      { xPercent: 0 },
      0
    )
    .fromTo(
      images[index],
      { xPercent: 125 * direction, scaleX: 1.5, scaleY: 1.3 },
      { xPercent: 0, scaleX: 1, scaleY: 1, duration: 1 },
      0
    )
    .fromTo(
      images[currentIndex.value],
      { xPercent: 0, scaleX: 1, scaleY: 1 },
      { xPercent: -125 * direction, scaleX: 1.5, scaleY: 1.3 },
      0
    )
    .fromTo(
      slideImages[index],
      { scale: 2 },
      { scale: 1 },
      0
    )

  // Optional heading animations if elements exist
  if (currentHeading && nextHeading) {
    tl.to(
      currentHeading,
      { '--width': 800, xPercent: 30 * direction },
      0
    )
      .fromTo(
        nextHeading,
        { '--width': 800, xPercent: -30 * direction },
        { '--width': 200, xPercent: 0 },
        0
      )
  }

  tl.timeScale(0.8)
}

// Helper function to wrap index
const wrapIndex = (index: number) => {
  const slidesLength = props.slidesData?.length ?? 0
  if (slidesLength === 0) return 0
  return (index + slidesLength) % slidesLength
}

// Navigation functions
const nextSlide = () => {
  gotoSection(currentIndex.value + 1, 1)
  resetAutoPlay()
}

const prevSlide = () => {
  gotoSection(currentIndex.value - 1, -1)
  resetAutoPlay()
}

// Auto-play controls
const startAutoPlay = () => {
  stopAutoPlay()
  autoPlayInterval.value = setInterval(nextSlide, autoPlayDelay)
}

const stopAutoPlay = () => {
  if (autoPlayInterval.value) {
    clearInterval(autoPlayInterval.value)
    autoPlayInterval.value = null
  }
}

const resetAutoPlay = () => {
  stopAutoPlay()
  startAutoPlay()
}

// Initialize component
const init = () => {
  if (!$gsap) {
    console.error('GSAP not found')
    return
  }

  const outerWrappers = $gsap.utils.toArray('.slide__outer')
  const innerWrappers = $gsap.utils.toArray('.slide__inner')

  $gsap.set(outerWrappers, { xPercent: 100 })
  $gsap.set(innerWrappers, { xPercent: -100 })
  $gsap.set('.slide:nth-of-type(1) .slide__outer', { xPercent: 0 })
  $gsap.set('.slide:nth-of-type(1) .slide__inner', { xPercent: 0 })

  startAutoPlay()
}

// Lifecycle hooks
onMounted(() => {
  init()
})

onUnmounted(() => {
  stopAutoPlay()
})
</script>

<style scoped>
::-webkit-scrollbar {
  display: none;
}

/* Font Face */
@font-face {
  font-family: 'Bandeins Sans & Strange Variable';
  src: url('https://res.cloudinary.com/dldmpwpcp/raw/upload/v1566406079/BandeinsStrangeVariable_esetvq.ttf');
}

/* Swiper Container */
.swiper-container {
  position: relative;
  height: 100vh;
  width: 100%;
  overflow: hidden;
}

/* Slides */
.slide {
  position: absolute;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
  visibility: hidden;
}

.slide--active {
  visibility: visible;
}

.slide__outer,
.slide__inner {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.slide__content {
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  height: 100%;
  width: 100%;
  top: 0;
}

.slide__container {
  position: relative;
  max-width: 1400px;
  width: 100vw;
  margin: 0 auto;
  height: 90vh;
  margin-bottom: 10vh;
  display: grid;
  grid-template-columns: repeat(10, 1fr);
  grid-template-rows: repeat(10, 1fr);
  gap: 0;
  padding: 0 1rem;
}

.slide__heading {
  --width: 200;
  display: block;
  text-align: left;
  font-family: 'Bandeins Sans & Strange Variable';
  font-size: clamp(5rem, 15vw, 15rem);
  font-weight: 900;
  font-variation-settings: 'wdth' var(--width);
  margin: 0;
  padding: 0;
  color: #f2f1fc;
  z-index: 999;
  mix-blend-mode: difference;
  grid-area: 2 / 2 / 3 / 10;
  align-self: end;
}

.slide__img-cont {
  margin-top: 4rem;
  grid-area: 2 / 1 / 7 / 8;
}

.slide__img-cont img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* Overlay */
.overlay-wrapper {
  position: relative;
  height: 100%;
  width: 100%;
}

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2;
  pointer-events: none;
}

.overlay__content {
  max-width: 1400px;
  width: 100vw;
  margin: 0 auto;
  padding: 0 1rem;
  height: 90vh;
  margin-bottom: 10vh;
  display: grid;
  grid-template-columns: repeat(10, 1fr);
  grid-template-rows: repeat(10, 1fr);
  gap: 0;
}

.overlay__img-cont {
  position: relative;
  overflow: hidden;
  margin: 0;
  grid-area: 4 / 3 / 9 / 11;
}

.overlay__img-cont img {
  position: absolute;
  width: 100%;
  height: 100%;
  object-fit: cover;
  object-position: 50% 50%;
  opacity: 0;
  z-index: 0;
}

.overlay__img-cont .image--active {
  opacity: 1;
  z-index: 1;
}

.overlay__count {
  grid-area: 3 / 10 / 4 / 10;
  font-size: clamp(3rem, 4vw, 15rem);
  margin: 0;
  padding: 0;
  text-align: right;
  border-bottom: 7px white solid;
}

/* Navigation Buttons */
.swiper-button {
  position: fixed;
  top: 50%;
  transform: translateY(-50%);
  width: 60px;
  height: 60px;
  background: rgba(255, 255, 255, 0.2);
  border: none;
  border-radius: 50%;
  color: white;
  font-size: 2rem;
  cursor: pointer;
  z-index: 10;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;

  &:hover {
    background: rgba(255, 255, 255, 0.4);
  }
}

.swiper-button--prev {
  left: 40px;
}

.swiper-button--next {
  right: 40px;
}

/* Footer */
footer {
  position: absolute;
  z-index: 999;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 2rem;
  width: 100%;
  height: 7em;
  font-family: 'Sora', sans-serif;
  font-size: clamp(1.2rem, 2vw, 1rem);
}

footer a {
  color: #fff;
  text-decoration: none;
}

/* Responsive Styles */
@media screen and (min-width: 900px) {

  .overlay__content,
  .slide__container {
    padding: 0 3rem;
    margin-top: 10vh;
    height: 80vh;
  }

  .overlay__img-cont {
    grid-area: 5 / 4 / 10 / 11;
  }

  .overlay__count {
    grid-area: 3 / 10 / 4 / 11;
  }

  .slide__img-cont {
    margin-top: 0;
    grid-area: 3 / 2 / 8 / 7;
  }

  .slide__heading {
    grid-area: 1 / 1 / 4 / 10;
  }
}
</style>